<template>
    <div id="print" ref="fatherbbbsss">
    <div class="title" ><i class="el-icon-arrow-left" v-show="!showDetails" style="margin-right:30px;cursor: pointer;font-size:18px;font-weight:1000;" @click="blackAudio()"></i><i style="font-size:.1rem;" class="iconfont icon-yinpin"></i> 音频列表
      <el-button style="float:right;margin-left:10px;margin-right:10px;margin-top:6px;color:#fff;" type="text" @click="printPdf"><i class="el-icon-printer"></i> {{$t('wechat.dayinSms')}}</el-button>
    </div>
    <transition name="el-zoom-in-center">
    <div v-show="showDetails" class="audioBoxList" @scroll="handleScroll()" ref="audioListBBB">

      <!-- <el-table :data="tableData" height="80vh" border stripe style="width: 100%">
        <el-table-column prop="date" label="语音" width="400">
          <template slot-scope="scope">
            <p>本地路径:{{scope.row.path}}</p>
              <el-button size="small" @click="detailsAuideInfo(scope.row)">播放</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="fileName" label="文件名" width="180">
        </el-table-column>
        <el-table-column prop="filesize" label="大小（kb）">
          <template slot-scope="scope">
            {{scope.row.filesize}}

          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template slot-scope="scope">
            <div class="badgeBox" v-if="scope.row.cntRemark>0">{{$t('wechat.remarked')}}</div>
            <el-button class="orderBtn" :title="$t('wechat.biaojitishi')" v-else @click="markOrder(scope.row)"  size="mini" style="margin-right:20px;float:right;color: #000;" icon="el-icon-edit">{{$t('wechat.biaoji')}}</el-button>
          </template>
        </el-table-column>
      </el-table> -->
      <!-- <el-table-column prop="validvalue" label="md5"> </el-table-column> -->
      <!-- <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="offset"
            :page-sizes="[20, 30, 40, 50]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
      </div> -->

      <div @click="openAudioDetails(item)" class="item" v-for="(item,index) in audioListbb" :key="index">
        <svg width="44" height="44" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M24 44C35.0457 44 44 35.0457 44 24C44 12.9543 35.0457 4 24 4C12.9543 4 4 12.9543 4 24C4 35.0457 12.9543 44 24 44Z" fill="#54a3f8" stroke="#54a3f8" stroke-width="4"/><path d="M30 18V30" stroke="#FFF" stroke-width="4" stroke-linecap="round"/><path d="M36 22V26" stroke="#FFF" stroke-width="4" stroke-linecap="round"/><path d="M18 18V30" stroke="#FFF" stroke-width="4" stroke-linecap="round"/><path d="M12 22V26" stroke="#FFF" stroke-width="4" stroke-linecap="round"/><path d="M24 14V34" stroke="#FFF" stroke-width="4" stroke-linecap="round"/></svg>
        <div style="margin-left:10px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width:240px;" :title="item.filemd5">{{ item.filemd5 }}</div>
        <div style="margin-left:10px;"><svg width="44" height="44" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M19 12L31 24L19 36" stroke="#9e9e9e" stroke-width="2" stroke-linecap="square" stroke-linejoin="round"/></svg></div>
        <div class="fileSizeBox">时间：{{ formDate(item.msgtime) }}</div>
      </div>

      <!-- 尾部加载 -->
      <div class="loadingBox" v-if="showLoading" style="color:#2196f3"><i :class="loadClass" style="color:#2196f3"></i> {{ loadingText }}</div>
    </div>
  </transition>
    <div class="audioBoxList" v-if="!showDetails">
      <div style="padding:30px 10px;">
        <audio v-if="IsMp3(audioDataItem.respath)" style="width:100%;" controls :src="audioDataItem.respath" controlsList="nodownload noplaybackrate"></audio>
        <audio v-if="!IsMp3(audioDataItem.respath)" style="width:100%;" controls :src="codeSrc" controlsList="nodownload noplaybackrate"></audio>
      </div>
      <h3 style="font-weight: bold;padding-left:10px;height:34px;border-bottom:1px solid #e7e7e7;line-height: 34px;margin-bottom:5px;">音频信息:</h3>
        <div style="padding-left:10px;min-height:40px;line-height: 40px;border-bottom: 1px solid #efe9e9;" ><i class="el-icon-warning-outline"></i> 若音频不能播放，请点击转码后播放！ <el-link type="primary" style="float: right;margin-right:20px;" @click="codeFormate(audioDataItem)"><i v-if="showTime" class="el-icon-loading"></i> {{$t('wechat.playzhuanma')}}</el-link><el-link title="点击跳定位到聊天" type="primary" style="" @click.stop="positionMessage(audioDataItem)">定位到聊天</el-link></div>
        <div style="padding-left:10px;min-height:40px;line-height: 40px;border-bottom: 1px solid #efe9e9;"><i class="el-icon-folder"></i> 时间：{{ formDate(audioDataItem.msgtime) }}</div>
        <div style="padding-left:10px;min-height:40px;line-height: 40px;border-bottom: 1px solid #efe9e9;"><i class="el-icon-files"></i> 来源：{{audioDataItem.contactname}}</div>
        <div style="padding-left:10px;min-height:40px;line-height: 40px;border-bottom: 1px solid #efe9e9;"><i class="el-icon-lock"></i> MD5：{{ audioDataItem.validvalue }}</div>
        <div style="padding-left:10px;min-height:40px;line-height: 40px;border-bottom: 1px solid #efe9e9;word-wrap: break-word;"><i class="el-icon-guide"></i> {{$t('wechat.imgPath')}}:{{ audioDataItem.respath }}</div>
    </div>
    <a-modal
      title="语音详情"
      :maskClosable="false"
      :getContainer="getRefsAff"
      :footer="null"
      width="85%"
      @cancel="handleCancel"
      :visible="visibleAudio"
    >
    <div class="audioBox">
      <div class="pathBox">
        <div class="itemAudio bottomBorder" style="border-top-right-radius: 5px;">
          <audio v-if="!showDetails" ref="audioDom" :src="codeSrc" controls></audio>
          文件名：{{audioData.fileName}}
          <el-button size="small" style="margin-left:20px;" @click="playAudioFile(audioData.respath)" v-html="html"></el-button>
        </div>
        <div class="itemAudio" style="border-bottom-right-radius: 5px;">
          <i class="el-icon-document-copy copy" @click.stop="copyAddress(audioData.respath)" title="复制" style="margin-right:10px;"></i>本地路径：{{audioData.path}}
        </div>
      </div>
    </div>
    </a-modal>

    <a-modal width="300px" v-model="showRemark" :getContainer="getRefsAff"
      :maskClosable="false" title="提示" @ok="handleOk">
      <p>{{$t('wechat.biaojibeizhu')}}</p>
      <p><el-input type="textarea" v-model="remark"></el-input></p>
    </a-modal>
  </div>
</template>

<script>
import print from 'print-js'
import html2canvas from "html2canvas"
import { getWxMediaInfo,getFormateCode } from '@/api/weChat/weChat_api'
import formateCodeLoading from "@/views/mainComponents/formateCodeLoading/index.vue"
import { parseTime } from '@/utils/index'
import { sendMarkOrderApi } from '@/api/markApi/index'
export default {
  name: "wxAudio",
  props:['sendData'],
  components:{
      formateCodeLoading
  },
  data() {
    return {
      scrollTopData:0,
      audioListbb:[],
      showLoading:false,
      loadClass:'el-icon-loading',
      loadingText:'正在加载. . .',
      showTime:false,
      audioDataItem:'',
      showDetails:true,
      showRemark:false,
      remark:'',
      id:'',
      codeSrc:'',
      visibleAudio:false,
      timeNumber:0,
      html:'点击转码',
      play: false,
      offset:1,
      limit:20,
      total:0,
      index:null,
      audioData:'',
      tableData: [
        {
          date: "2016-05-02",
          path:'http://downsc.chinaz.net/Files/DownLoad/sound1/201906/11582.mp3',
          name: "100kb",
          address: "fjhakjnfbkajbakjbkjdgfbf",
        },
        {
          date: "2016-05-04",
          path:'http://downsc.chinaz.net/Files/DownLoad/sound1/201906/11582.mp3',
          name: "100kb",
          address: "fjhakjnfbkajbakjbkjdgfbf",
        },
        {
          date: "2016-05-01",
          path:'http://downsc.chinaz.net/Files/DownLoad/sound1/201906/11582.mp3',
          name: "100kb",
          address: "fjhakjnfbkajbakjbkjdgfbf",
        },
        {
          date: "2016-05-03",
          path:'http://downsc.chinaz.net/files/download/sound1/201206/1638.mp3',
          name: "100kb",
          address: "fjhakjnfbkajbakjbkjdgfbf",
        },
      ],
    };
  },
  watch:{
    '$store.state.account.weChat':function(){
      if(this.sendData.list_offset){
      this.offset=1;
      this.limit=20*this.sendData.list_offset;
    }else{
      this.offset=1
    }
    this.audioListbb = [];
    this.showDetails = true;
      this.init()
    }
  },
  created(){
    if(this.sendData.list_offset){
      this.offset=1;
    this.limit=20*this.sendData.list_offset;
    }else{
      this.offset=1
    }
    this.init();
  },
  methods: {
    // 定位到聊天
    positionMessage(item){
    //   this.$nextTick(() => {
    //   // this.scrollTop = this.$refs.audioListBBB.scrollTop;

    // });
      // return
        this.showDetails = true;
        item['proof_num'] = this.sendData.proof_num;
        item['username'] = sessionStorage.getItem('usernameTitle');
        item['model'] = 'wechat';
        item['msgtime'] = item.msgtime;
        item['contact_username'] = item.contactname;
        item['id'] = item.id;
        item['list_offset'] = this.offset;
        // item['list_offset'] = this.sendData.list_offset?this.sendData.list_offset:this.offset;
        item['msg_offset'] = 1;
        item['app_name'] = item.contactname.includes('@')?'群组':'好友';
        item['wxChildrenNode'] = true;
        item['scrollTop'] = this.scrollTopData;
        item['childrenModel'] = 'WXaudio';
        item['account_id'] = this.sendData.account_id;




        // 储存类型
        sessionStorage.setItem('model',"wechat")
        // 储存节点数据
        sessionStorage.setItem('sumData',JSON.stringify(item))
        // 激活跳转组件
        this.$store.commit('SET_ORDERDATA',Date.parse(new Date()))
        sessionStorage.setItem('only',true);
      },
    // 下拉加载
    handleScroll(){
      // 获取列表元素
      const list = this.$refs.audioListBBB;
      this.scrollTopData = list.scrollTop;
      // 判断滚动到底部
      if (list.scrollTop + list.clientHeight+10+5 >= list.scrollHeight) {
        this.showLoading=true;

        if(this.audioListbb.length<this.total){
          this.loadClass = 'el-icon-loading';
          this.loadingText = '正在加载. . .';
          this.offset++;
          // 加载更多数据
          let that = this;
              that.init();
        }else{
          this.loadClass = 'el-icon-success';
          this.loadingText = '到底了，没有更多了！';

        }

      }
    },
    IsMp3(path){
      if(path.includes('.')){
        let extension = path.split('.').pop();
      extension.toLowerCase();
      if(extension.toLowerCase()=='mp3'){
        return true;
      }else{
        return false;
      }
      }else{
        return false;
      }
      
    },
    codeFormate(url){
      this.showTime = true;
      let suffix = '';
      if(url.respath.includes('.')){
        suffix = /\.([0-9a-zA-Z]+)$/i.exec(url.respath)[1]
      }else{
        suffix = null;
      }
      if(suffix!=='mp3' || suffix==null){
        let data={
          mediaPath:url.respath,
          mediaType:1
        }
        getFormateCode(data).then(res=>{
          this.showTime = false;
          // this.showLoadingBox=false
          this.codeSrc=res.data[0].direction;

        }).catch(err=>{
          // this.showLoadingBox=false
        })
      }else{
        this.showTime = false;
        // this.html=`无需转码<i class="el-icon-check"/>`
        this.codeSrc=url
      }
    },
    blackAudio(){
      this.audioDataItem = '';
      this.codeSrc = '';
      this.showDetails = true;
    },
    openAudioDetails(item){
      this.audioDataItem = item;
      this.showDetails = false;
    },
    handleOk(){
        let data={
          navigation_list:sessionStorage.getItem('arr').split(','),
          model:this.sendData.model,
          isChat:0,
          app_name:'',
          account_id:'',
          subtype:this.sendData.subtype,
          proof_num:this.sendData.proof_num,
          list_offset:this.offset,
          list_limit:this.limit,
          remark:this.remark,
          class:this.sendData.class,
          label:this.sendData.label,
          id:Number(this.id)
    }
      sendMarkOrderApi(data).then(res=>{
        this.showRemark=false;
        this.$message({
          message: '标记数据成功！',
          type: 'success'
        });
        this.init()
      })
    },
    // 添加标记点
    markOrder(item){
      this.id=item.id;
      this.showRemark=true;
    },
  copyAddress(valueData) {
    let oInput = document.createElement("input");
    //这边为链接地址this.liveLink='www.baidu.com'
    oInput.value = valueData;
    document.body.appendChild(oInput);
    oInput.select();
    document.execCommand("Copy");
    oInput.remove();
    this.$message({
      message: "复制成功",
      type: "success",
    });
  },
    getRefsAff(){
      return  this.$refs.fatherbbbsss
    },
    handleCancel(e) {
      this.codeSrc=''
      this.html='点击转码'
      this.visibleAudio = false;
    },
    initSuffix(){

    },
    // 播放语音
    playAudioFile(url){
      this.html=`正在转码请稍后...<i class="el-icon-loading"/>`
      let suffix = /\.([0-9a-zA-Z]+)$/i.exec(url)[1]
      if(suffix!=='mp3'){
        let data={
          mediaPath:url.respath,
          mediaType:1
        }
        getFormateCode(data).then(res=>{
          this.html=`转码完成<i class="el-icon-check"/>`
          // this.showLoadingBox=false
          this.codeSrc=res.data[0].direction

        }).catch(err=>{
          // this.showLoadingBox=false
        })
      }else{
        this.html=`无需转码<i class="el-icon-check"/>`
        this.codeSrc=url
      }

    },
    formDate(date){
      return parseTime(date)
    },
    detailsAuideInfo(item){
      this.html='点击转码'
      this.audioData=item
      this.visibleAudio=true
    },
    init(){
      let data={
        proof_num:this.sendData.proof_num,
        account_id:this.sendData.account_id,
        offset:this.offset,
        limit:this.limit
      }
      getWxMediaInfo(data,'/tencent/audio/list').then(res=>{
        this.showLoading=false;

        for (let index = 0; index < res.data.length; index++) {
          const element = res.data[index];
          this.audioListbb.push(element)
        }
        try {
        this.total = res.data[0].cnt;
        if(this.sendData.list_offset){
          this.$nextTick(() => {
            this.$refs.audioListBBB.scrollTop=this.sendData.scrollTop;
          })
          this.offset = this.sendData.list_offset
          this.limit = 20;
        }

        } catch (error) {
          // this.total=0;
        }
      })
    },
    //导出(pdf)
    savePdf(){
    },
    //打印
    printPdf(){
        html2canvas(document.getElementById('print')).then(function(canvas) {
          var imgageData = canvas.toDataURL("image/png");//把canvas转为base64图片
          print(imgageData, 'image');
        });
    },
    // 音频时长
    returnAudioTime(e){
      let musicDom = e.path[0].lastChild;

      return parseInt(musicDom.duration)
    },
    playAudio(e, id,row) {
      //开始转码
      this.index=id
      let data={
        mediaPath:row.path,
        mediaType:1
      }
      getFormateCode(data).then(res=>{
        this.tableData[id].path=res.data[0].direction
      try{
        this.index=null;
        // 开始播放
      this.play=!this.play
      if (this.play) {
        e.path[0].childNodes[1].className = "bg voicePlayActive";
        // let musicDom = this.$refs.music;
        let musicDom = e.path[0].lastChild;
        musicDom.play();
        let that=this;
        setTimeout(function () {
          e.path[0].childNodes[1].className = "bg voicePlay";
        }, musicDom.duration * 1000);
      }else{
        let musicDom = e.path[0].lastChild;
        musicDom.pause();
        e.path[0].childNodes[1].className = "bg voicePlay";
      }
      }catch{
        this.index=null;
      }

      })
    },
    handleSizeChange(val) {
      this.limit=val
      this.init()
    },
    handleCurrentChange(val) {
      this.offset=val
      this.init()
    },
  },
};
</script>

<style scoped>

.fileSizeBox{
  position: absolute;
  bottom:0px;
  right: 50px;
  font-size: 12px;
  color:#b2b2b2;
}
.audioBoxList{
  height: 95%;
  overflow: hidden;
  padding-bottom:50px;
  overflow-y: auto;
}

.audioBoxList::-webkit-scrollbar {
  width: 8px;
}
/* <!--修改 滚动条的 下面 的 样式--> */
.audioBoxList::-webkit-scrollbar-track {
  background-color: rgb(252, 252, 252);
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
}
/* <!--修改 滑块 --> */
.audioBoxList::-webkit-scrollbar-thumb {
  background-color: #dfdfdf;
  -webkit-border-radius: 2em;
  -moz-border-radius: 2em;
  border-radius: 2em;
}
.item{
  height: 60px;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 10px;
  justify-content: space-between;
  position: relative;
  border-bottom: 1px solid #e8e8e8;
}
.item:hover{
  background: #e7e7e7;
}
.badgeBox{
  width: 50px;
  height: 23px;
  border-radius: 10px;
  color: #fff;
  background: #f56c6c;
  text-align: center;
  line-height: 23px;
  font-size: 12px;
}
.biaozhuimg{
  width: 60px;
  height: 60px;
  position: absolute;
  right: 20px;
  bottom: 10px;
}
.copy{
  font-size: 20px;
  cursor: pointer;
}
.copy:hover{
  color: #409eff;
}
#print{
  position: relative;
}
.itemAudio{
  height: 39px;
  background: #f3f3f3;
  width: 100%;
  padding: 9.3px;
  display: flex;
  align-items: center;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.loadingBox{
  position: relative;
  top: 10px;
  text-align: center;
}
.numberActive{
  position: absolute;
  color: #fff;
  right: 0;
}
.block {
  text-align: center;
  margin-top: 15px;
}
.pathBox{
  height: .5rem;
  width: 100%;
}
.audioBox{
  width: 100%;
  height: .5rem;
  display: flex;
  padding: 0 .1rem;
}
.title {
  height: 50px;
  line-height: 50px;
  font-size: 0.1rem;
  background: #2b2f3a;
  color: #fff;
  padding-left: 20px;
}

.voice {
  position: relative;
  padding-top: 5px;
  padding-left: 10px;
  margin: 0px auto;
  height: 35px;
  width: 150px;
  background: #2b2f3a;
  /* border-radius: 0 7px 7px; */
  border-radius: 5px;
  cursor: pointer;
}

.bg {
  background: url()
    right 0 no-repeat;
  width: 24px;
  height: 24px;
  background-size: 400%;
}

.voicePlay {
  /* animation-name: voicePlay; */
  /* animation-duration: 1s;
  animation-direction: normal;
  animation-iteration-count: infinite;
  animation-timing-function: steps(3); */
}

.voicePlayActive {
  animation-name: voicePlay;
  animation-duration: 1s;
  animation-direction: normal;
  animation-iteration-count: infinite;
  animation-timing-function: steps(3);
}

@keyframes voicePlay {
  0% {
    background-position: 0;
  }
  100% {
    background-position: 100%;
  }
}
</style>
